package com.sanwei.dialer;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private EditText mPhoneLabel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mPhoneLabel = findViewById(R.id.phoneNumber);
        mPhoneLabel.setEnabled(true);
        mPhoneLabel.setFocusable(true);
        mPhoneLabel.setFocusableInTouchMode(true);
        mPhoneLabel.requestFocus();
        mPhoneLabel.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                call();
            }
            return false;
        });

        ImageButton call = findViewById(R.id.dialerButton);
        call.setOnClickListener(view -> call());

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(view -> {
            Snackbar.make(view, "Call phone: 10086", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
            call("10086");
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d(TAG, "onKeyDown: " + keyCode);
        switch (keyCode) {
            case KeyEvent.KEYCODE_CALL:
            case KeyEvent.KEYCODE_NUMPAD_ENTER:
            case KeyEvent.KEYCODE_ENTER:
                call();
            break;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void call(){
        CharSequence phone = mPhoneLabel.getText();
        if (!TextUtils.isEmpty(phone)) {
            mPhoneLabel.setText("");
            call(phone);
        }else {
            Snackbar.make(mPhoneLabel, "Call phone: is Empty, please input Number", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    }

    private void call(CharSequence phone){
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + phone));
        startActivity(intent);
    }

}
